package com.gm.wholesale.module.order.view;
import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.gm.commonlib.filters.RegexConstant;
import com.gm.commonlib.filters.RegexResultFilter;
import com.gm.commonlib.util.numberUtils.DigitUtil;
import com.gm.commonlib.util.numberUtils.NumberUtils;
import com.gm.commonlib.util.viewUtils.RepeatClickUtils;
import com.gm.commonlib.views.popupwindow.Popupwindow;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.R;
import com.gm.wholesale.constant.PayMethod;
import com.gm.wholesale.module.good.bean.GoodBean;
import com.gm.wholesale.module.order.bean.OrderPayInfoBean;
import com.gm.wholesale.module.order.bean.WebViewUseBean;
import com.gm.wholesale.module.settlement.bean.CustomerSettlementBean;
import com.gm.wholesale.view.MyTextWatcher;
import com.gm.wholesale.view.NumberInputView;

import java.util.List;

public class PayMoneyView extends LinearLayout {
    public static final int PAY_TYPE_UNPAY=1; //未支付单子，进行支付
    public static final int PAY_TYPE_PARTIAL_PAYMENT=2; //待结算进入
    private View mianView;
    private TextView headerLableTv;
    private View preferentiaView;

    private TextView allPriceTv;
    private ImageView closeView;
    public EditText payPriceEd;

    public EditText preferentialEd;
    public EditText actualPaymentEd;
    private NumberInputView numberInputView;

    private TextView lable1Tv;

    private TextView realityPayTv;
    private List<GoodBean> mGoodBeans;
    public double mTotalPrice;
    private RadioGroup payMethodRg;
    private double mNeedPayMoney;

    private int payMethod;

    private boolean mIsFromWeb;


    public interface OnCreateOrderListener {
        void onCreateSuccess();
    }

    private OnSubmitClickListener listener;

    public void setOnSubmitClickListener(OnSubmitClickListener listener) {
        this.listener = listener;
    }

    public interface OnSubmitClickListener {
        void onSubmitClick(OrderPayInfoBean payInfoBean, List<GoodBean> goodBeans);
    }

    public PayMoneyView(Context context) {
        super(context);
        initView(context);
    }

    public PayMoneyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }


    private void initData() {
        payMethod = PayMethod.WX.getType();
        mTotalPrice = 0;
        if (mGoodBeans != null) {
            mGoodBeans.clear();
            mGoodBeans = null;
        }

    }

    private void initView(Context context) {
        initData();
        LayoutInflater.from(context).inflate(R.layout.view_submit_order, this);
        mianView=findViewById(R.id.mainView);
        preferentiaView=findViewById(R.id.preferentiaView);
        headerLableTv=findViewById(R.id.headerLableTv);
        realityPayTv=findViewById(R.id.realityPayTv);
        lable1Tv = findViewById(R.id.lable1Tv);
        allPriceTv = findViewById(R.id.allPriceTv);
        closeView = findViewById(R.id.closeView);
        payPriceEd = findViewById(R.id.payPriceEd);
        payPriceEd.setEnabled(false);
        preferentialEd = findViewById(R.id.preferentialEd);
        actualPaymentEd = findViewById(R.id.actualPaymentEd);
        numberInputView = findViewById(R.id.numberInputView);
        payMethodRg = findViewById(R.id.payMethodRg);
        preferentialEd.setFilters(new InputFilter[]{new RegexResultFilter(RegexConstant.MAX_MONEY_VALUE_92)});
        actualPaymentEd.setFilters(new InputFilter[]{new RegexResultFilter(RegexConstant.MAX_MONEY_VALUE_92)});
        closeView.setOnClickListener(view -> Popupwindow.hiddenPop());
        mianView.setOnClickListener(v -> Popupwindow.hiddenPop());
        preferentialEd.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {
                    String preferentMoney = editable.toString();
                    if (!TextUtils.isEmpty(preferentMoney)) {
                        double money = NumberUtils.subDouble(mNeedPayMoney, Double.parseDouble(preferentMoney));
                        if (money<=0){
                            actualPaymentEd.setText("0");
                            return;
                        }
                        actualPaymentEd.setText(NumberUtils.getMoneyString(money));
                    }
                    else {
                        actualPaymentEd.setText(NumberUtils.getMoneyString(mNeedPayMoney));
                    }

            }
        });
        preferentialEd.setOnFocusChangeListener((view, b) -> {
            if (b) {
                numberInputView.bindEdiText(preferentialEd, preferentialEd.getText().toString());
            }
        });
        actualPaymentEd.setOnFocusChangeListener((view, b) -> {
            if (b) {
                numberInputView.bindEdiText(actualPaymentEd, actualPaymentEd.getText().toString());
            }
        });

        payMethodRg.setOnCheckedChangeListener((radioGroup, i) -> {
            if (i == R.id.payMethodWx) {
                payMethod = PayMethod.WX.getType();
            } else if (i == R.id.payMethodWxZfb) {
                payMethod = PayMethod.ZFB.getType();
            } else {
                payMethod = PayMethod.XJ.getType();
            }

        });
        //todo 提交按钮
        numberInputView.setINumberView(() -> {
            if (RepeatClickUtils.check()){
                return;
            }
            String toPayMoneys = actualPaymentEd.getText().toString();
            //优惠
            String discountAmounts = preferentialEd.getText().toString();

            double toPayMoney = -1;
            double discountAmount = -1;
            if (!TextUtils.isEmpty(toPayMoneys)) {
                toPayMoney = Double.parseDouble(toPayMoneys);
            }
            if (!TextUtils.isEmpty(discountAmounts)) {
                discountAmount = Double.parseDouble(discountAmounts);
            }
            if (toPayMoney < 0 && discountAmount < 0) {
                ToastUtil.showToast("请输入本次收款");
                return;
            }
//            if (toPayMoney<0){
//                ToastUtil.showToast("本次收款不能小于0");
//                return;
//            }
            double needPay=NumberUtils.addDouble(toPayMoney, discountAmount);
            double payMoney= DigitUtil.parseDouble(needPay,2);
            if ( payMoney> DigitUtil.parseDouble(mTotalPrice,2)) {
                if (mIsFromWeb){
                    ToastUtil.showToast("本次收款不能大于欠款金额");
                }
                else {
                    ToastUtil.showToast("本次收款不能大于应收金额");
                }
                return;
            }

            OrderPayInfoBean payInfoBean = new OrderPayInfoBean();

            if (!TextUtils.isEmpty(discountAmounts)) {
                payInfoBean.setDiscountAmount(discountAmounts);
            } else {
                payInfoBean.setDiscountAmount("0");
            }
            //支付方式
            payInfoBean.setPayment(payMethod);
            //实际支付费用
            payInfoBean.setPaidAmount(toPayMoneys);
            if (listener != null) {
                listener.onSubmitClick(payInfoBean, mGoodBeans);
            }


        });

    }


    public void updateView(List<GoodBean> goodBeans) {
        mTotalPrice = 0;
        this.mGoodBeans = goodBeans;
        for (GoodBean goodBean : goodBeans) {
            mTotalPrice = NumberUtils.addDouble(goodBean.getTotalPrice()) + mTotalPrice;
        }
        String totalMoney = NumberUtils.getMoneyString(mTotalPrice);
        mNeedPayMoney = mTotalPrice;
        payPriceEd.setText(totalMoney);
        actualPaymentEd.setText(totalMoney);
        allPriceTv.setText("￥" + totalMoney);
        //重置为空
        preferentialEd.setText("");

        lable1Tv.setText("应收");
    }

    public void showViewByWebViewUse(WebViewUseBean viewUseBean) {
        mIsFromWeb=true;
        mNeedPayMoney = viewUseBean.getDebtAmount();
        lable1Tv.setText("欠款金额");
        allPriceTv.setText("￥" + NumberUtils.getMoneyString(viewUseBean.getSalesAmount()));
        mTotalPrice = viewUseBean.getDebtAmount();
        String payMoney = NumberUtils.getMoneyString(viewUseBean.getDebtAmount());
        payPriceEd.setText(payMoney);
        actualPaymentEd.setText(payMoney);

    }


    public void showPayMoney(int type,CustomerSettlementBean waitToAccuntBean) {
        if (type==PAY_TYPE_UNPAY){ //未支付，调用,支付金额取ShouldPayAmount
            mNeedPayMoney = waitToAccuntBean.getShouldPayAmount();
        }
        else { //待结算进入，金额取
            mNeedPayMoney = waitToAccuntBean.getBalanceAmount();
        }
        numberInputView.bindEdiText(preferentialEd,"");
        preferentialEd.requestFocus();
        lable1Tv.setText("应收");
        allPriceTv.setText("￥" + NumberUtils.getMoneyString(waitToAccuntBean.getTotalAmount()));
        mNeedPayMoney=Math.abs(mNeedPayMoney);
        mTotalPrice = mNeedPayMoney;
        String payMoney = NumberUtils.getMoneyString(mNeedPayMoney);
        payPriceEd.setText(payMoney);
        actualPaymentEd.setText(payMoney);

    }


    // todo 订单详情收款功能使用
    public void showViewByGetMoney(double salesAmount, double needMoney) {
        headerLableTv.setText("销售金额:");
        mNeedPayMoney = needMoney;
        mTotalPrice = needMoney;
        String payMoney = NumberUtils.getMoneyString(needMoney);
        payPriceEd.setText(payMoney);
        allPriceTv.setText(NumberUtils.getMoneyWithUnitStrig(salesAmount));
        actualPaymentEd.setText(payMoney);
        numberInputView.bindEdiText(preferentialEd,"");
        preferentialEd.requestFocus();


    }
}
